import DownOutlined from '@ant-design/icons-vue/lib/icons/DownOutlined'
import {
  Button,
  Dropdown,
  Menu,
  MenuItem,
  message,
  Upload
} from 'ant-design-vue'
import moment from 'moment'
import { defineComponent, ref } from 'vue'

import { riverApi } from '@/apis'
import { type ProTableProps, type ProTableRef, ProTable } from '@/components'
import UploadFile from '@/components/UploadFile'
import { FILE_TYPE, STATUS } from '@/components/UploadFile/types'
import { TABLE_ITEM_RENDER, TABLE_RENDERER } from '@/constants'
import { useDialog } from '@/hooks'
import router from '@/router'
import { downloadLinkWithoutName } from '@/utils'

import { bankTypeOptions } from '../constants'

export default defineComponent({
  name: 'RvUploadReceipt',
  setup() {
    const tableRef = ref({} as ProTableRef)
    const uploadLoading = ref(false)
    const bankName = ref('')
    const excelList = ref([] as any[])
    const tableConfig = ref({
      fixedHeight: true,
      options: {
        border: true,
        align: 'center',
        toolbarConfig: {
          perfect: false,
          slots: {
            buttons: 'toolbarButtons'
          }
        },
        formConfig: {
          items: [
            {
              title: '银行',
              field: 'bank',
              itemRender: {
                name: TABLE_ITEM_RENDER.ASelect,
                options: bankTypeOptions,
                props: {
                  placeholder: '全部',
                  allowClear: true
                }
              }
            },
            {
              title: '导入时间',
              field: 'timeRange',
              itemRender: {
                name: TABLE_RENDERER.FormItemDate,
                props: {
                  type: 'range',
                  placeholder: ['开始时间', '结束时间'],
                  valueFormat: 'x',
                  showTime: {
                    defaultValue: [
                      moment('00:00:00', 'HH:mm:ss'),
                      moment('23:59:59', 'HH:mm:ss')
                    ]
                  },
                  keys: ['importStart', 'importEnd']
                }
              }
            },
            {
              title: '操作人',
              field: 'name',
              itemRender: {
                name: TABLE_ITEM_RENDER.AInput,
                props: {
                  placeholder: '请输入',
                  allowClear: true
                }
              }
            },
            {
              itemRender: {
                name: TABLE_RENDERER.FormItemBtns
              }
            }
          ]
        },
        columnConfig: {
          minWidth: 150,
          resizable: true
        },
        columns: [
          {
            type: 'seq',
            width: 50,
            title: '序号'
          },
          {
            title: '回单流水号',
            field: 'serialNo',
            width: 300
          },
          {
            title: '银行',
            field: 'bank',
            width: 100
          },
          {
            title: '导入附件链接',
            field: 'link',
            slots: {
              default: 'receiptImg'
            }
          },
          {
            title: '新增回单条数',
            width: 100,
            slots: {
              default: 'quantity'
            }
          },
          {
            title: '操作人',
            field: 'operator',
            width: 200
          }
        ],
        pagerConfig: {
          pageSize: 15
        },
        proxyConfig: {
          form: true,
          props: {
            result: 'dataList',
            total: 'page.totalCount'
          },
          ajax: {
            query: async ({ page, form }) => {
              const data = await riverApi.getReceiptList({
                pageParameter: {
                  pageSize: page.pageSize,
                  currentPage: page.currentPage
                },
                ...form
              })
              return data
            }
          }
        }
      }
    } as ProTableProps)

    //新增回单
    function handleAdd(e) {
      bankName.value = e.key
    }

    function checkFile(file) {
      const isExcel = file.name.toLowerCase().match(/\.(xls|xlsx)$/) != null
      if (!isExcel) {
        message.error('Excel格式不正确')
      }
      return isExcel
    }

    async function onUploadChange(file: any) {
      try {
        const formData = new FormData()
        formData.append('file', file.file)
        formData.append('bank', bankName.value)
        excelList.value = await riverApi.uploadReceipt(formData)
        tableRef.value.refresh()
        message.error('导入成功')
      } catch {
        message.error('导入失败')
      }
    }
    // async function onUploadChange(fileList: any, status: STATUS) {
    //   if (status == STATUS.UPLOADING) {
    //     uploadLoading.value = true
    //   } else {
    //     if (status == STATUS.DONE) {
    //       try {
    //         await riverApi.uploadReceipt(bankName.value, fileList[0].url)
    //         tableRef.value.refresh()
    //       } finally {
    //         uploadLoading.value = false
    //       }
    //     } else {
    //       uploadLoading.value = false
    //     }
    //   }
    // }

    //回单详细
    function handelDetail(item: any) {
      router.push({
        name: 'RvReceiptSubDetailList',
        query: {
          id: item.serialNo
        }
      })
    }

    return {
      tableRef,
      tableConfig,
      uploadLoading,
      handleAdd,
      handelDetail,
      onUploadChange,
      checkFile
    }
  },
  render() {
    return (
      <div>
        <ProTable
          ref="tableRef"
          v-slots={{
            toolbarButtons: () => {
              return (
                <Dropdown
                  v-slots={{
                    overlay: () => {
                      return (
                        <Upload
                          showUploadList={false}
                          accept=".xlsx,.xls"
                          name="file"
                          beforeUpload={this.checkFile}
                          customRequest={this.onUploadChange}
                          // hideUploadUpLimit={false}
                          // onChange={this.onUploadChange}
                          // fileType={'excel'}
                        >
                          <Menu onClick={this.handleAdd}>
                            {/* <MenuItem key="中国银行">中国银行</MenuItem> */}
                            <MenuItem key="鄞州银行">鄞州银行</MenuItem>
                          </Menu>
                        </Upload>
                      )
                    }
                  }}
                >
                  <Button loading={this.uploadLoading} type="primary">
                    上传回单
                    <DownOutlined />
                  </Button>
                </Dropdown>
              )
            },
            receiptImg: ({ row }) => {
              return (
                <Button
                  type="link"
                  style={{ whiteSpace: 'pre-wrap' }}
                  onClick={() => {
                    downloadLinkWithoutName(row.link, row.link)
                  }}
                >
                  {row.link}
                </Button>
              )
            },

            quantity: ({ row }) => {
              return (
                <Button
                  type="link"
                  onClick={() => {
                    this.handelDetail(row)
                  }}
                >
                  {row.receiptNum}
                </Button>
              )
            }
          }}
          {...this.tableConfig}
        />
      </div>
    )
  }
})
